import json
import os
import urllib.request

def request(action, **params):
    return {'action': action, 'params': params, 'version': 6}

def invoke(action, **params):
    requestJson = json.dumps(request(action, **params)).encode('utf-8')
    response = json.load(urllib.request.urlopen(urllib.request.Request('http://127.0.0.1:8765', requestJson)))
    if len(response) != 2:
        raise Exception('response has an unexpected number of fields')
    if 'error' not in response:
        raise Exception('response is missing required error field')
    if 'result' not in response:
        raise Exception('response is missing required result field')
    if response['error'] is not None:
        raise Exception(response['error'])
    return response['result']

def findCards(deckname):
    return invoke('findCards', query="deck:" + deckname)

def moveCards(cards, dst_deck):
    return invoke('changeDeck', cards=cards, deck=dst_deck)

def delete_decks(decks_name, del_cards = True):
    return invoke('deleteDecks', decks=decks_name, cardsToo=del_cards)

def get_all_decks_name():
    return invoke('deckNames')

def get_sub_deck(deck_name, level = 1):
    decks_name = get_all_decks_name()
    parent_levels = deck_name.split("::")
    parent_depth = len(parent_levels)
    
    # 筛选直接子牌组
    direct_subdecks = []
    for deck in decks_name:
        deck_levels = deck.split("::")
        # 判断层级是否符合条件
        if (
            deck.startswith(deck_name + "::")  # 以父牌组开头
            and len(deck_levels) == parent_depth + level
            and deck_levels[:parent_depth] == parent_levels  # 前N级与父牌组一致
        ):
            direct_subdecks.append(deck)
    return direct_subdecks

def create_deck(deck_name):
    return invoke('createDeck', deck = deck_name)

def import_file(file_path):
    return invoke('guiImportFile', path = file_path)

def list_files(directory, sfx = '.txt'):
    txt_files = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith(sfx):
                txt_files.append(os.path.join(root, file))
    return txt_files

def import_files(dir_path):
    for file_path in list_files(dir_path, '.txt'):
        import_file(file_path)

# import_file(r"D:\MyData\XYQ\code\gitee\for_children_projects\output\anki_import_data01.txt")
# import_file(r"D:\MyData\XYQ\code\gitee\for_children_projects\output\anki_import_data02.txt")
# print(list_files(r"D:\MyData\XYQ\code\gitee\for_children_projects\output"))
import_files(r"D:\MyData\XYQ\code\gitee\for_children_projects\output")

# # res = findCards("All::1_Life::育儿::徐韬略::幼儿园::大班下学期::3_英语::3_other")
# # res = get_all_decks_name()
# parent_decks = "All::1_Life::育儿::徐韬略::幼儿园::大班下学期::3_英语::3_other"
# sub_decks = get_sub_deck(parent_decks, 2)
# # print(sub_decks)
# for deck in sub_decks:
#     rel_path = deck.removeprefix(parent_decks)
#     # print(rel_path)
#     dr_path = "All::1_Life::育儿::徐韬略::幼儿园::大班下学期::3_英语::1_认读" + rel_path;
#     sr_path = parent_decks + rel_path + "::1_认读";
#     print(sr_path)
#     dw_path = "All::1_Life::育儿::徐韬略::幼儿园::大班下学期::3_英语::2_听写" + rel_path;
#     sw_path = parent_decks + rel_path + "::2_听写";
#     # print(r_path)
#     # print(w_path)
#     # create_deck(r_path)
#     # create_deck(w_path)
#     r_cards = findCards(sr_path)
#     w_cards = findCards(sw_path)
#     print(r_cards)
#     moveCards(r_cards, dr_path)
#     moveCards(w_cards, dw_path)
#     # break


# invoke('createDeck', deck='test1')
# for i in range(1, 2):
    # deck_for_read = "All::1_Life::育儿::徐韬略::幼儿园::大班下学期::3_英语::1_认读::20250220::" + str(i)
    # deck_for_write = "All::1_Life::育儿::徐韬略::幼儿园::大班下学期::3_英语::2_听写::20250220::" + str(i)
    # cards_for_read_ID = findCards(deck_for_read);
    # cards_for_write_ID = findCards(deck_for_write);
    # print('cards ID: {}'.format(cards_ID))
    # moveCards(cards_ID, "All::1_Life::育儿::徐韬略::幼儿园::大班下学期::3_英语::2_听写::1_20250220::" + str(i))
    # moveCards(cards_for_read_ID, deck_for_write)
    # moveCards(cards_for_write_ID, deck_for_read)
    # delete_decks(["All::1_Life::育儿::徐韬略::幼儿园::大班下学期::3_英语::1_认读::20250220::" + str(i) + "::1_认读"]);
# for i in range(4, 9):
    # delete_decks(["All::1_Life::育儿::徐韬略::幼儿园::大班下学期::3_英语::20250220::" + str(i) + "::2_听写"]);